package com.heima.comment.service.imp;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustomException;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dto.CommentRepayDto;
import com.heima.model.comment.dto.CommentRepayLikeDto;
import com.heima.model.comment.dto.CommentRepaySaveDto;
import com.heima.model.comment.pojo.ApComment;
import com.heima.model.comment.pojo.ApCommentLike;
import com.heima.model.comment.pojo.ApCommentRepay;
import com.heima.model.comment.pojo.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVo;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author TheCai
 * @date 2021/6/5 22:23
 */
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
  @Autowired private MongoTemplate mongoTemplate;
  @Autowired private UserFeign userFeign;
  @Autowired GreenTextScan greenTextScan;

  /**
   * 根据评论id查询回复列表
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult loadCommentRepay(CommentRepayDto dto) {
    // 1.检查参数(size  分页10条)
   Integer size= dto.getSize();
    if (size == null || size <= 0) {
      size=10;
    }
    // 2.根据评论id  最小时间    size  按照创建时间降序查询数据
    Query query =
        Query.query(
                Criteria.where("commentId")
                    .is(dto.getCommentId())
                    .and("createdTime")
                    .lt(dto.getMinDate()))
            .with(Sort.by(Sort.Direction.DESC, "createdTime"))
            .limit(size);
    List<ApCommentRepay> commentRepays = mongoTemplate.find(query, ApCommentRepay.class);

    // 3.判断用户是否登录,没登录直接返回数据
    ApUser user = AppThreadLocalUtils.getUser();
    if (user == null || commentRepays == null || commentRepays.isEmpty()) {
      // 3.1没登录直接封装结果返回
      return ResponseResult.okResult(commentRepays);

    }
    // 4.如果登陆了,判断哪些回复登录用户点过赞
    //抽取当前页所有回复id
    List<String> commentRepaysIds = commentRepays.stream()
            .map(ApCommentRepay::getId)
            .collect(Collectors.toList());

    Query apCommentLikeQuery = Query.query(Criteria.where("authorId")
            .is(user.getId()).and("commentRepayId").in(commentRepaysIds));
    //在当前分页数据下,登录用户所点赞过得所有数据
    List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(apCommentLikeQuery, ApCommentRepayLike.class);

    //这里抽取的是点赞里的评论id,这样我们就得到了点过赞的评论ID
    List<String> repayLikeIds = apCommentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());

    List<ApCommentRepayVo>apCommentRepayVoList=new ArrayList<>();
    //转为vo
    commentRepays.forEach(commentRepay->{
              ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
              BeanUtils.copyProperties(commentRepay,apCommentRepayVo);

      if (repayLikeIds.contains(commentRepay.getId())){
        apCommentRepayVo.setOperation((short)0);
      }
      apCommentRepayVoList.add(apCommentRepayVo);
    });


    return ResponseResult.okResult(apCommentRepayVoList);
}
  /**
   * 保存回复评论
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {

    // 1.检查参数(评论id  方式  是否登录)
    ApUser user = AppThreadLocalUtils.getUser();
    if (user == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }
    // 2.远程获取登录用户信息
    user = userFeign.findUserById(user.getId());
    if (user == null) {
      throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST, "未获取到用户id");
    }

    // 3.阿里云文本检测
    boolean isTextScan = handleTextScan(dto.getContent()); // 阿里云文本审核
    if (!isTextScan) {
      return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不符合要求,请重新编辑");
    }
    ;
    log.info("=======当前处理的文章通过阿里云文本审核======当前处理的文章id======= {}", dto.getCommentId());

    // 4.保存评论回复信息
    ApCommentRepay apCommentRepay = new ApCommentRepay();
    apCommentRepay.setAuthorId(user.getId());
    apCommentRepay.setAuthorName(user.getName());
    apCommentRepay.setContent(dto.getContent());
    apCommentRepay.setCommentId(dto.getCommentId());
    apCommentRepay.setCreatedTime(new Date());
    apCommentRepay.setUpdatedTime(new Date());
    apCommentRepay.setLikes(0);
    mongoTemplate.insert(apCommentRepay);

    // 5.更新评论信息的回复信息
    ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
    apComment.setReply(apComment.getReply() + 1);
    mongoTemplate.save(apComment);

    return ResponseResult.okResult();
  }

  /**
   * 点赞评论
   *
   * @param dto
   * @return
   */
  @Override
  public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
    // 1.检查参数

    // 2.判断是否登录
    ApUser user = AppThreadLocalUtils.getUser();
    if (user == null) {
      return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
    }

    // 查询评论信息
    ApCommentRepay commentRepay =
        mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);

    if (commentRepay == null) {
      throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
    }
    // 保证不会重复点赞

    Query query =
        Query.query(
            Criteria.where("authorId")
                .is(user.getId())
                .and("commentRepayId")
                .is(dto.getCommentRepayId()));
    ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
    if (apCommentRepayLike != null && dto.getOperation().intValue() == 0) {
      return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已点赞");
    }

    // 3.点赞操作
    if (dto.getOperation().intValue() == 0) {
      // 更新评论的点赞数量
      commentRepay.setLikes(commentRepay.getLikes() + 1);
      // 保存 APP评论信息点赞
      apCommentRepayLike = new ApCommentRepayLike();
      apCommentRepayLike.setAuthorId(user.getId());
      apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
      apCommentRepayLike.setOperation(dto.getOperation());

      mongoTemplate.insert(apCommentRepayLike);

    } else {
      // 4.取消点赞
      // 更新评论的点赞数量
      commentRepay.setLikes(commentRepay.getLikes() <= 0 ? 0 : (commentRepay.getLikes() - 1));
      mongoTemplate.save(commentRepay);
      // 更新 APP评论信息点赞
      mongoTemplate.remove(query, ApCommentRepayLike.class);
    }

    // 5.数据返回
    Map map =new HashMap();
    map.put("likes",commentRepay.getLikes());
    return ResponseResult.okResult(map);
  }

  /**
   * 阿里云文本审核
   *
   * @param
   * @return
   */
  private boolean handleTextScan(String text) {
    Boolean flag = false;
    try {
      Map map = greenTextScan.greenTextScan(text);
      // 阿里云给出的审核结果,建议
      String suggestion = map.get("suggestion").toString();
      System.out.println("阿里云评测结果============>>" + suggestion);
      if ("pass".equals(suggestion)) {
        // 只有pass通过,其他一律不让过
        flag = true;
      }
    } catch (Exception e) {
      e.printStackTrace();
      flag = false;
    }
    return flag;
  }
}
